package com.rao.security.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * ajax请求登录失败处理器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 22:22
 */
@Component
public class MyFailureHandler implements AuthenticationFailureHandler {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    /**
     * 参数说明：
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param ae       spring security框架验证用户信息失败后的异常封装对象
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException ae) throws IOException, ServletException {
        // 当框架验证用户信息失败时执行的方法
        response.setContentType("text/json;charset=utf-8");

        if (result == null) {
            result = new Result(1, 1001, "登录失败");
        }

        OutputStream out = response.getOutputStream();
        ObjectMapper om = new ObjectMapper();
        om.writeValue(out, result);
        out.flush();
        out.close();
    }

}
